<?php
/**
 * 安装向导
 */
header('Content-type:text/html;charset=utf-8');
if (is_file('../data/install.lock')) {
	echo '你已经安装过该系统，重新安装需要先删除./data/install.lock 文件';
    exit;
}

function get_sql($sql_file) {
        $contents = file_get_contents($sql_file);
        $contents = str_replace("\r\n", "\n", $contents);
        $contents = trim(str_replace("\r", "\n", $contents));
        $return_items = $items = array();
        $items = explode(";\n", $contents);
        foreach ($items as $item) {
            $return_item = '';
            $item = trim($item);
            $lines = explode("\n", $item);
            foreach ($lines as $line) {
                if (isset($line[1]) && $line[0] . $line[1] == '--') {
                    continue;
                }
                $return_item .= $line;
            }
            if ($return_item) {
                $return_items[] = $return_item; //.";";
            }
        }
        return $return_items;
    }

// 同意协议页面
if(@!isset($_GET['c']) || @$_GET['c']=='agreement'){
    require './agreement.html';
}
// 检测环境页面
if(@$_GET['c']=='test'){
    require './test.html';
}
// 创建数据库页面
if(@$_GET['c']=='create'){
    require './create.html';
}
// 安装成功页面
if(@$_GET['c']=='success'){
    // 判断是否为post
    if($_SERVER['REQUEST_METHOD']=='POST'){
        $data=$_POST;
		
		 if (!$data['DB_HOST'] || !$data['DB_PORT'] || !$data['DB_USER'] || !$data['DB_PWD'] || !$data['DB_NAME'] || !$data['user'] || !$data['pwd']) {
               die("<script>alert('信息填写不完整');history.go(-1)</script>");
              exit;
          }
		
        // 连接数据库
        $link=@new mysqli("{$data['DB_HOST']}:{$data['DB_PORT']}",$data['DB_USER'],$data['DB_PWD']);
        // 获取错误信息
        $error=$link->connect_error;
        if (!is_null($error)) {
            // 转义防止和alert中的引号冲突
            $error=addslashes($error);
            die("<script>alert('数据库链接失败:$error');history.go(-1)</script>");
        }
        // 设置字符集
        $link->query("SET NAMES 'utf8'");
        $link->server_info>5.0 or die("<script>alert('请将您的mysql升级到5.0以上');history.go(-1)</script>");
        // 创建数据库并选中
        if(!$link->select_db($data['DB_NAME'])){
            $create_sql='CREATE DATABASE IF NOT EXISTS '.$data['DB_NAME'].' DEFAULT CHARACTER SET utf8;';
            $link->query($create_sql) or die('创建数据库失败');
            $link->select_db($data['DB_NAME']);
        }
        $sqls =get_sql('./Sql_data/initdata.sql');
        $admin_pass = md5($data['pwd']);
		$data['admin_email']=$data['user'].'@qq.com';
        $sqls[] = "INSERT INTO `" . $data['DB_PREFIX'] . "admin` (`id`,`username`, `password`, `email`, `role_id`) VALUES " .
                "(1,'" . $data['user'] . "', '" . $admin_pass . "', '" . $data['admin_email'] . "', 1);";
        foreach ($sqls as $sql) {
            $sql = str_replace('`tqk_', '`' . $data['DB_PREFIX'], $sql);
            $sql = str_replace('tqk_', $data['DB_PREFIX'], $sql);
          //  if (substr($sql, 0, 11) == 'INSERT INTO') {
                $table_name = $data['DB_PREFIX'] . preg_replace("/INSERT INTO `" . $data['DB_PREFIX'] . "([a-z0-9_]+)` .*/is", "\\1", $sql);
                //$run = mysql_query($sql, $link);
				 $link->query($sql);
           
		  // }
        }
		
        $link->close();
        $db_str=<<<php
<?php
return array(

//*************************************数据库设置*************************************
    'DB_TYPE'               =>  'mysqli',                 // 数据库类型
    'DB_HOST'               =>  '{$data['DB_HOST']}',     // 服务器地址
    'DB_NAME'               =>  '{$data['DB_NAME']}',     // 数据库名
    'DB_USER'               =>  '{$data['DB_USER']}',     // 用户名
    'DB_PWD'                =>  '{$data['DB_PWD']}',      // 密码
    'DB_PORT'               =>  '{$data['DB_PORT']}',     // 端口
    'DB_PREFIX'             =>  '{$data['DB_PREFIX']}',   // 数据库表前缀
);
php;
        // 创建数据库链接配置文件
        file_put_contents('../data/Config/db.php', $db_str);
        @touch('../data/install.lock');
        require './success.html';
    }

}

